package com.mason.forum.service.impl;

import com.mason.forum.common.ResultCode;
import com.mason.forum.dao.ArticleMapper;
import com.mason.forum.exception.ApplicationException;
import com.mason.forum.model.Article;
import com.mason.forum.model.Board;
import com.mason.forum.model.User;
import com.mason.forum.model.vo.ArticleVO;
import com.mason.forum.service.IArticleService;
import com.mason.forum.service.IBoardService;
import com.mason.forum.service.IUserService;
import com.mason.forum.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-06
 * Time: 17:31
 */
@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    //一定要避免出现循环引用的问题
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;


    @Override
    public void publish(Article article) {
        // 0. 参数校验
        if(article == null || !StringUtils.hasLength(article.getContent(), article.getTitle())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 1. 设置默认值
        article.setVisitCount(0); //访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0); // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 2. 写入数据库
        int rows = articleMapper.insertSelective(article);
        if(rows != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(ResultCode.FAILED_CREATE);
        }
        // 3. 新增成功
        log.info(ResultCode.SUCCESS.toString() + "新增成功: art id: "
                + article.getId() + ". ");
    }

    @Override
    public void create(Article article) {
        // 1. 发布文章
        publish(article);
        // 2. 板块帖子数 + 1
        boardService.incrementArticleCountById(article.getBoardId());
        // 3. 用户帖子数 + 1
        userService.incrementArticleCountById(article.getUserId());
        // 4. 成功
        log.info(ResultCode.SUCCESS.toString() + " 发帖成功: art id: "
                + article.getId() + ". ");
    }

    @Override
    public List<ArticleVO> selectAll() {
        // 调用dao层
        List<ArticleVO> articleVOS = articleMapper.selectAll();
        // 返回结果
        return articleVOS;
    }

    @Override
    public List<ArticleVO> selectAllByBoardId(Long boardId) {
        // 0. 参数校验
        if(boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 1. 查询board是否可用
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + " board id：" + boardId);
            throw new ApplicationException(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        if(board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString() + " board id：" + boardId);
            throw new ApplicationException(ResultCode.FAILED_BOARD_BANNED);
        }
        // 2. dao层
        List<ArticleVO> articleVOS = articleMapper.selectAllByBoardId(boardId);
        // 3. 返回结果
        return articleVOS;
    }

    @Override
    public ArticleVO selectDetailByAid(Long id) {

        // 参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // dao层 - 查询详情
        ArticleVO articleVO = articleMapper.selectDetailByAid(id);
        // 校验帖子
        if(articleVO == null) {
            //帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(articleVO.getDeleteState() == 1 || articleVO.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // dao层 - 阅读量自增
        ArticleVO updateArt = new ArticleVO();
        updateArt.setId(id);
        updateArt.setVisitCount(articleVO.getVisitCount() + 1);
        int rows = articleMapper.updateByPrimaryKeySelective(updateArt);
        // 校验rows
        if(rows != 1) {
            //自增失败
            log.warn(ResultCode.FAILED_ARTICLE_Visit_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_Visit_COUNT);
        }
        // 成功返回
        return articleVO;//这个的阅读量是自增之前的，也可以是之后，我觉得之前会更合适
    }

    @Override
    public void modify(Long id, String title, String content) {
        // 0. 参数校验
        if(id == null || id <= 0 || !StringUtils.hasLength(title, content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 1. 构建修改信息模板
        Article updateArt = new Article();
        updateArt.setId(id);
        updateArt.setTitle(title);
        updateArt.setContent(content);
        updateArt.setUpdateTime(new Date());//修改时间为现在
        // 2. dao层 - 修改信息
        int rows = articleMapper.updateByPrimaryKeySelective(updateArt); //有无权限在controller层判断
        // 校验
        if(rows != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(ResultCode.ERROR_SERVICES);
        }
        // 3. 更新成功
        log.info(ResultCode.SUCCESS.toString() + "更新成功: art id: "
                + id + ". ");
    }

    @Override
    public Article selectById(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // dao层 - 查询详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验帖子
        if(article == null) {
            //帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 成功返回
        return article;
    }

    @Override
    public void thumpUp(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // dao层 - 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null) {
            //帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getDeleteState() == 1 || article. getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 构造修改对象
        Article updateArt = new Article();
        updateArt.setId(id);
        updateArt.setLikeCount(article.getLikeCount() + 1);
        //  dao层 - 修改信息
        int rows = articleMapper.updateByPrimaryKeySelective(updateArt);
        // 校验
        if(rows != 1) {
            log.warn(ResultCode.FAILED_ARTICLE_LIKE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_LIKE_COUNT);
        }
        // 更新成功
        log.info(ResultCode.SUCCESS.toString() + "更新成功: art id: "
                + id + ". ");
    }

    @Override
    public void offShelf(Long id) {
        // 参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 构造修改对象（更新时间是用户头像之类的信息更改才修改）
        Article updateArt = new Article();
        updateArt.setId(id);//修改的时候通过的是主键
        updateArt.setDeleteState((byte) 1);//删除
        // dao层 - ”删除帖子“
        int rows = articleMapper.updateByPrimaryKeySelective(updateArt);
        // 校验
        if(rows != 1) {
            log.warn(ResultCode.FAILED_ARTICLE_DELETE.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_DELETE);
        }
        // 删除成功
        log.info(ResultCode.SUCCESS.toString() + "删除成功: art id: "
                + id + ". ");
    }

    @Override
    public void deleteById(Article article) {
        // 1. 下架文章
        offShelf(article.getId());
        // 2. 板块帖子数 - 1
        boardService.decrementArticleCountById(article.getBoardId());
        // 3. 用户帖子数 - 1
        userService.decrementArticleCountById(article.getUserId());
        // 4. 成功
        log.info(ResultCode.SUCCESS.toString() + " 发帖成功: art id: "
                + article.getId() + ". ");
    }

    @Override
    public void incrementReplyCount(Long id) {

        // 1. 参数校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_BOARD_ARTICLE_COUNT);
        }
        // 2. dao层 - 获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null) {
            //帖子不存在
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getDeleteState() == 1 || article. getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 3. 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setId(article.getId());//更新时需要主键
        // 4. dao层 - 更新帖子回复数
        int rows = articleMapper.updateByPrimaryKeySelective(updateArticle);//更新一个值就够了
        if(rows != 1) {
            log.warn(ResultCode.FAILED_ARTICLE_REPLY_COUNT.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_REPLY_COUNT);
        }
        // 更新成功
        log.info(ResultCode.SUCCESS.toString() + "更新成功: art id: "
                + id + ". ");
    }

    @Override
    public List<ArticleVO> selectAllByUserId(Long userId) {
        // 参数校验
        if(userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 用户必须存在
        User user = userService.selectById(userId);
        if(user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " user id：" + userId);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 2. dao层
        List<ArticleVO> articleVOS = articleMapper.selectAllByUserId(userId);
        // 3. 返回结果
        return articleVOS;
    }



}
